// pages/orders/orders.js
const apiService = require('../../utils/apiService.js');

Page({
  data: {
    activeStatus: 0,
    allOrders: [], // 所有订单
    orders: [], // 当前显示的订单
    statusMap: ['全部', '进行中', '已完成', '已取消'],
    statusCounts: [0, 0, 0, 0], // 各状态订单数量
    loading: false,
    refreshing: false,
    searchValue: '',
    showSearch: false
  },

  onLoad() {
    this.loadOrdersData();
  },

  onShow() {
    this.loadOrdersData();
  },

  // 加载订单数据
  async loadOrdersData() {
    this.setData({ loading: true });
    
    try {
      // 调用API获取我的订单
      const apiOrders = await apiService.getMyOrders();
      // console.log('API返回的订单数据:', apiOrders);
      
      // 转换API订单数据格式
      const formattedOrders = apiOrders.map(order => ({
          id: order.order_id || order.id,
          orderNumber: order.orderId || order.order_number || order.id || '未知订单',
          restaurant: order.room?.title || '未知餐厅',
          dishes: order.dishes || [],
          status: order.status, // 保持原始状态值用于筛选
          statusText: this.mapOrderStatus(order.status),
          statusColor: this.getStatusColor(order.status),
          createTime: order.createdAt || order.created_at || '未知时间',
          itemCount: (order.dishes || []).reduce((sum, dish) => sum + (dish.quantity || 0), 0),
          deliveryTime: null
      }));
      
      // console.log('格式化后的订单数据:', formattedOrders);
      
      this.setData({
        allOrders: formattedOrders,
        loading: false,
        refreshing: false
      });
      this.updateStatusCounts();
      this.filterOrdersByStatus();
      
    } catch (error) {
      
      // 如果API失败，清空数据
      setTimeout(() => {
        // 清除本地存储中的旧数据
        wx.removeStorageSync('orders');
        
        this.setData({
          allOrders: [],
          loading: false,
          refreshing: false
        });
        this.updateStatusCounts();
        this.filterOrdersByStatus();
      }, 500);
    }
  },

  // 映射订单状态
  mapOrderStatus(apiStatus) {
    const statusMap = {
      'pending': '待确认',
      'confirmed': '已确认',
      'processing': '制作中',
      'ready': '待取餐',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[apiStatus];
  },



  // 状态切换
  onStatusChange(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeStatus: index
    });
    
    this.filterOrdersByStatus();
  },

  // 更新状态统计
  updateStatusCounts() {
    const { allOrders } = this.data;
    const counts = [0, 0, 0, 0]; // 全部、进行中、已完成、已取消
    
    allOrders.forEach(order => {
      counts[0]++; // 全部
      if (['pending', 'processing', 'ready'].includes(order.status)) {
        counts[1]++; // 进行中
      } else if (['completed', 'confirmed'].includes(order.status)) {
        counts[2]++; // 已完成
      } else if (order.status === 'cancelled') {
        counts[3]++; // 已取消
      }
    });

    this.setData({
      statusCounts: counts
    });
  },

  // 根据状态筛选订单
  filterOrdersByStatus() {
    const { allOrders, activeStatus, searchValue } = this.data;
    let filteredOrders = [];

    switch (activeStatus) {
      case 0: // 全部
        filteredOrders = allOrders;
        break;
      case 1: // 进行中
        filteredOrders = allOrders.filter(order => 
          ['pending', 'processing', 'ready'].includes(order.status)
        );
        break;
      case 2: // 已完成
        filteredOrders = allOrders.filter(order => ['completed', 'confirmed'].includes(order.status));
        break;
      case 3: // 已取消
        filteredOrders = allOrders.filter(order => order.status === 'cancelled');
        break;
    }

    // 如果有搜索条件，进行搜索过滤
    if (searchValue) {
      filteredOrders = filteredOrders.filter(order => 
        order.orderNumber.includes(searchValue) ||
        order.restaurant.includes(searchValue) ||
        order.dishes.some(dish => dish.name.includes(searchValue))
      );
    }

    this.setData({
      orders: filteredOrders
    });
  },

  // 下拉刷新
  onRefresh() {
    this.setData({ refreshing: true });
    this.loadOrdersData();
  },


  // 查看订单详情
  viewOrderDetail(e) {
    const order = e.currentTarget.dataset.order;
    
    // 跳转到订单详情页
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?orderId=${order.id}`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: '确认取消',
      content: `确定要取消订单${order.orderNumber}吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await apiService.cancelOrder(order.id);
            // 刷新订单列表数据
            await this.loadOrdersData();
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
          } catch (error) {
            wx.showToast({
              title: '取消订单失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  // 确认订单
  async confirmOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: '确认订单',
      content: `确定要确认订单${order.orderNumber}吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await apiService.confirmOrder(order.id);
            // 刷新订单列表数据
            await this.loadOrdersData();
            wx.showToast({
              title: '订单已确认',
              icon: 'success'
            });
          } catch (error) {
            wx.showToast({
              title: '确认订单失败',
              icon: 'error'
            });
          }
        }
      }
    });
  },

  // 更新订单状态
  updateOrderStatus(orderId, status, statusText) {
    const { allOrders } = this.data;
    const updatedOrders = allOrders.map(order => {
      if (order.id === orderId) {
        return {
          ...order,
          status: status,
          statusText: statusText,
          statusColor: this.getStatusColor(status)
        };
      }
      return order;
    });

    this.setData({
      allOrders: updatedOrders
    });
    this.filterOrdersByStatus();
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'pending': 'warning',
      'confirmed': 'info',
      'processing': 'info',
      'ready': 'primary',
      'completed': 'success',
      'cancelled': 'tertiary'
    };
    return colorMap[status];
  },

  // 评价订单
  rateOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showToast({
      title: '评价功能开发中',
      icon: 'none'
    });
  },

  // 再次下单
  reorder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showToast({
      title: '再次下单功能开发中',
      icon: 'none'
    });
  },

  // 去点单
  goToOrder() {
    wx.switchTab({
      url: '/pages/order/order'
    });
  },

  // 搜索功能
  onSearchClick() {
    this.setData({
      showSearch: !this.data.showSearch
    });
  },

  // 切换搜索框显示
  toggleSearch() {
    this.setData({
      showSearch: !this.data.showSearch
    });
  },

  onSearchChange(e) {
    this.setData({
      searchValue: e.detail
    });
    this.filterOrdersByStatus();
  },

  onSearchClear() {
    this.setData({
      searchValue: '',
      showSearch: false
    });
    this.filterOrdersByStatus();
  },

  // 修改订单
  editOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: '修改订单',
      content: '确定要修改这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 跳转到点单页面，并传递订单信息
          wx.navigateTo({
            url: `/pages/order/order?orderId=${order.id}&edit=true`
          });
        }
      }
    });
  },

  // 清空订单
  clearOrder(e) {
    const order = e.currentTarget.dataset.order;
    wx.showModal({
      title: '清空订单',
      content: '确定要清空这个订单吗？此操作不可撤销。',
      success: (res) => {
        if (res.confirm) {
          // 调用API清空订单
          this.clearOrderItems(order.id);
        }
      }
    });
  },

  // 清空订单项目
  async clearOrderItems(orderId) {
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 这里应该调用API清空订单
      // await apiService.clearOrder(orderId);
      
      // 暂时显示成功提示
      wx.hideLoading();
      wx.showToast({
        title: '订单已清空',
        icon: 'success'
      });
      
      // 重新加载订单数据
      this.loadOrdersData();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      });
    }
  }
});
